package com.itheima.security.springboot.dao;

import com.itheima.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * UserDao
 * </p>
 *
 * @author flyduck
 * @since 2023-11-20
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDto getUserByUsername(String username){
        String sql = "select id,username,password,fullname,mobile from t_user where username = ?";
        //连接数据库查询用户
        List<UserDto> userDtoList = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if(!CollectionUtils.isEmpty(userDtoList) || userDtoList.size() == 1){
            return userDtoList.get(0);
        }
        return null;

    }

    //根据用户id查询用户的权限
    public List<String> findPermissionsByUserId(String userId){
        String sql = "SELECT tp.* \n" +
                "FROM t_user_role tur\n" +
                "LEFT JOIN t_role_permission trp ON tur.role_id = trp.role_id\n" +
                "LEFT JOIN t_permission tp ON trp.permission_id = tp.id\n" +
                "WHERE user_id = ?";
        List<PermissionDto> permissionDtoList = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        return permissionDtoList.stream()
                .map(PermissionDto::getCode)
                .collect(Collectors.toList());
    }
}
